﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace ArgusControls
{
	public class TextFilter
	{
		List<int> lower;
		List<int> upper;

		public TextFilter()
		{
			this.lower = new List<int>();
			this.upper = new List<int>();
		}

		public TextFilter(int AsciiA, int AsciiB)
			:this()
		{
			this.AddAsciiRange(AsciiA, AsciiB);
		}

		public void AddAllowedCharacter(char c)
		{
			int v = (int)c;
			for (int i = 0; i < this.lower.Count; i++)
			{
				if (v >= this.lower[i] && v <= this.upper[i])
					return;
			}
			int l = this.lower.IndexOf(v+1);
			int u = this.upper.IndexOf(v - 1);
			if (l > -1 && u > -1)
			{
				this.lower[l] = this.lower[u];
				this.lower.RemoveAt(u);
				this.upper.RemoveAt(u);
			}
			else if (l > -1)
			{
				this.lower[l] = v;
			}
			else if (u > -1)
			{
				this.upper[u] = v;
			}
			else
			{
				this.AddAsciiRange(v, v);
			}
		}

		public void AddAllowedCharacterRange(char[] chars)
		{
			foreach (char ch in chars)
				this.AddAllowedCharacter(ch);
		}

		public void AddAllowedCharacterRange(string str)
		{
			this.AddAllowedCharacterRange(str.ToCharArray());
		}

		public void AddAsciiRange(int a, int b)
		{
			this.lower.Add(a);
			this.upper.Add(b);
		}

		public bool IsValid(char c)
		{
			int v = (int)c;
			for (int i = 0; i < this.lower.Count; i++)
			{
				if (v >= this.lower[i] && v <= this.upper[i])
					return true;
			}
			return false;
		}

		public string Filter(string text)
		{
			string RetVal = string.Empty;
			for (int i = 0; i < text.Length; i++)
			{
				if (this.IsValid(text[i]) == true)
					RetVal += text[i];
			}
			return RetVal;
		}
	}
}
